using System;
using System.Text;
using System.Data;
using Antu.Core.Services;

namespace Antu.Core.Ajax
{
	/// <summary>
	/// Provides methods to serialize and deserialize a DataRowView object.
	/// </summary>
	public class DataRowViewConverter : AbstractJavascriptConverter
	{
        private string _ClientType = "antu.objects.dataRow";
        SerializerService _SerializerService = (SerializerService)ServiceManager.Manager.GetService(typeof(SerializerService));
        /// <summary>
        /// Initializes a new instance of the <see cref="DataRowViewConverter"/> class.
        /// </summary>
		public DataRowViewConverter() : base()
		{
			allowInheritance = true;

			serializabletypeslist = new Type[] { typeof(DataRowView) };
		}

        /// <summary>
        /// Converts a .NET object into a JSON string.
        /// </summary>
        /// <param name="o">The object to convert.</param>
        /// <returns>Returns a JSON string.</returns>
		public override string Serialize(object o)
		{
			StringBuilder sb = new StringBuilder();
			Serialize(o, sb);
			return sb.ToString();
		}

        /// <summary>
        /// Serializes the specified o.
        /// </summary>
        /// <param name="o">The o.</param>
        /// <param name="sb">The sb.</param>
		public override void Serialize(object o, StringBuilder sb)
		{
			DataRowView row = o as DataRowView;

			if(row == null)
				throw new NotSupportedException();
			
			DataColumnCollection cols = row.DataView.Table.Columns;
			int colcount = cols.Count;

			bool b = true;

			sb.Append("new ");
			sb.Append(_ClientType);
			sb.Append("([");

			for(int i=0; i<colcount; i++)
			{
				if(b){ b = false; }
				else{ sb.Append(","); }

                _SerializerService.Serialize(row[cols[i].ColumnName], sb);
			}

			sb.Append("])");
		}
	}
}
